<?php
/**
 *base框架核心类
 */
namespace core;

use core\lib\route;//使用路由类
use core\lib\log;

class base
{

    //定义静态属性存储已加载的类
    public static $classMap = array();
    public $assign;

    /**
     * 启动框架
     */
    static public function run()
    {

        //启动日志
        log::init();
//        log::getLog('ceshi');
        $route = new route();
        $controller = $route->ctrl;     //控制嚣名
        $action = $route->action;   //方法名

        $controllerFile = APP . '/controllers/' . $controller . 'Controller.php';
        $controllerPath = '\\' . MODULE . '\controllers\\' . $controller . 'Controller';

        if (is_file($controllerFile)) {
            include $controllerFile;
            $ctrl = new $controllerPath();
            $ctrl->$action();
        } else {
            throw new \Exception('找不到控制器' . $controller);
        }
    }

    /**
     * 自动加载类库
     *  new \core\route();
     *  $class = '\core\route';
     *  MODULE.'/core/route.php';
     */
    static public function load($class)
    {

        /**
         * 要做的工作
         * 1：将 \ 替换为  /
         * 2：拼接类文件，路径
         */

        if (isset($classMap[$class])) {
            return true;
        } else {
            $class = str_replace('\\', '/', $class);
            $file = BS . '/' . $class . '.php';
            // debug(23);
            // debug($file);
            if (is_file($file)) {
                include $file;
                self:
                $classMap[$class] = $class;

            } else {
                return false;
            }
        }

    }

    //参数传值
    public function assign($name, $value)
    {
        $this->assign[$name] = $value;
    }

    //自定义视图渲染代码
    public function display($file, $value)
    {
        $filePath = APP . '/views/' . $file;
        if (is_file($filePath)) {

            $loader = new \Twig_Loader_Filesystem(APP . '/views');
            $twig = new \Twig_Environment($loader, array(
                'cache' => BS . '/log/twig',
                'debug' => DEBUG
            ));
            $template = $twig->load($file);
            $template->display($value ? $value : '');
        }
    }

    /**
     *
     * twig官方视图层渲染方法
     * @param $filename string
     * @param $value array
     */
    public function render($filename, $value)
    {
        $filePath = APP . '/views/' . $filename;

        // dump($value);
        if (is_file($filePath)) {
            $loader = new \Twig_Loader_Filesystem(APP . '/views');
            $twig = new \Twig_Environment($loader, array(
                'cache' => BS . '/log/twig',
                'debug' => DEBUG
            ));
            $template = $twig->load($filename);
            echo $template->render($value);
        }
    }

}